/**
 * @param {number[][]} grid
 * @param {number} row
 * @param {number} col
 * @param {number} color
 * @return {number[][]}
 */
var colorBorder = function(grid, row, col, color) {
  let tag = grid[row][col], canChange = new Array(grid.length), visited = new Array(grid.length);
  for(let i = 0; i < grid.length; i++) {
    canChange[i] = new Array(grid[0]).fill(false);
    visited[i] = new Array(grid[0]).fill(false);
  }
  // 判断位置是否有效
  function isValidPosition(i, j) {
    return (i < grid.length && i >= 0) && (j < grid[0].length && j >= 0);
  }
  function isBorder(i, j) {
    if((isValidPosition(i - 1, j) && grid[i - 1][j] == tag) && (isValidPosition(i + 1, j) && grid[i + 1][j] == tag) && (isValidPosition(i, j - 1) && grid[i][j - 1] == tag) && (isValidPosition(i, j + 1) && grid[i][j + 1] == tag))
      return false;
    else
      return true;
  }
  function dfs(i, j) {
    visited[i][j] = true;
    if(isBorder(i, j)) {
      canChange[i][j] = true;
    }
    // 上
    if(isValidPosition(i - 1, j) && grid[i - 1][j] == tag && !visited[i - 1][j]) {
      dfs(i - 1, j);
    }
    // 下
    if(isValidPosition(i + 1, j) && grid[i + 1][j] == tag && !visited[i + 1][j]) {
      dfs(i + 1, j);
    }
    // 左
    if(isValidPosition(i, j - 1) && grid[i][j - 1] == tag && !visited[i][j - 1]) {
      dfs(i, j - 1);
    }
    // 右
    if(isValidPosition(i, j + 1) && grid[i][j + 1] == tag && !visited[i][j + 1]) {
      dfs(i, j + 1);
    }
  }
  dfs(row, col);
  for(let i = 0; i < grid.length; i++) {
    for(let j = 0; j < grid[0].length; j++) {
      if(grid[i][j] && canChange[i][j]) {
        grid[i][j] = color;
      }
    }
  }
  return grid;
};
let grid = [[1,1],[1,2]], row = 0, col = 0, color = 3;
console.log(colorBorder(grid, row, col, color));
grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3;
console.log(colorBorder(grid, row, col, color));
grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2;
console.log(colorBorder(grid, row, col, color));
